package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("inventoryService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class InventoryService extends BaseServiceImpl<Inventory> {

	@Resource
	private InventoryDao inventoryDao;
	@Resource
	private UserDao userDao;
	@Resource
	private Memcached memcached;
	@Resource
	private ShopAdminUserDao shopAdminUserDao;
	@Resource
	private DdmShopDao ddmShopDao;
	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private SpecificationDao specificationDao;
	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Resource
	private InventoryLogDao inventoryLogDao;

	@Override
	protected BaseDao <Inventory> getDao() {
		return inventoryDao;
	}
	/*
	*CRM查询店铺商品库存
	 */
	public String getList(ModelMap model, String page,String shopId,String token,String code ,String name,String abbreviation,Boolean state){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(shopId)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		DdmShop ddmShop =ddmShopDao.getById(Integer.parseInt(shopId));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		Map<String, Object> search=new HashedMap();
		search.put("shopId",ddmShop.getId());
		search.put("name",name.equals("")?null:name);
		search.put("code",code.equals("")?null:code);
		search.put("abbreviation",abbreviation.equals("")?null:abbreviation);
		if(state!=null){
			search.put("state",state?1:0);
		}else {
			search.put("state",null);
		}
		pageview=inventoryDao.queryPageView(pageNo, pageSize,"getShopGoods",search);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmInventoryList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return new JSONObject(model).toString();
	}

	public List<ModelMap> convertCrmInventoryList(List<Inventory> inventoryList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (inventoryList != null && inventoryList.size() > 0) {
			for (Inventory inventory : inventoryList) {
				ModelMap map = buildModelCrmInventoryList(inventory);
				list.add(map);
			}
		}
		return list;
	}

	public ModelMap buildModelCrmInventoryList(Inventory inventory) {
		ModelMap model = new ModelMap();
		model.put("id",inventory.getId());
		model.put("goodsid",inventory.getGoodsId());
		model.put("shopName",inventory.getDdmShopList().get(0).getName());
		model.put("abbreviation",inventory.getDdmGoodsList().get(0).getAbbreviation());
		model.put("goodsName",inventory.getDdmGoodsList().get(0).getName());
		model.put("code",inventory.getDdmGoodsList().get(0).getCode());
		model.put("state",inventory.getDdmGoodsList().get(0).getState()?"有效":"无效");
		model.put("inventory",inventory.getInventory());
		model.put("propertiesName",inventory.getGoodSpecificationList().size()!=0?inventory.getGoodSpecificationList().get(0).getPropertiesName():"");
		return  model;
	}
/*
*商品入库
* zlq
* token：
* id：库存记录ID
* inventorySourceValue: 来源
* changeNum:改变的值
* remark:备注
 */
	public String goodsBePutInStorage(ModelMap model,String id,String token,String inventorySourceValue,String changeNum,String remark){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		if(!NumberUtils.isDigits(inventorySourceValue)){
			return CodeContent.getModelByCode(0, "库存来源不能为空", model);
		}
		if(InventorySource.getByIntValue(Integer.parseInt(inventorySourceValue))==null){
			return CodeContent.getModelByCode(0, "库存来源不匹配", model);
		}
		if(!NumberUtils.isDigits(changeNum)){
			return CodeContent.getModelByCode(0, "数量不能为空", model);
		}
		if(Integer.parseInt(changeNum)<1){
			return CodeContent.getModelByCode(0, "数量不能小于1", model);
		}
		Inventory inventory =inventoryDao.getById(Integer.parseInt(id));
		if(inventory==null){
			return CodeContent.getModelByCode(0, "库存ID不正确", model);
		}
		ShopAdminUser shopAdminUser=new ShopAdminUser();
		shopAdminUser.setShopId(inventory.getShopId());
		shopAdminUser.setUserId(loginUser.getId());
		List<ShopAdminUser> shopAdminUserList=shopAdminUserDao.queryPageView(-1,-1,shopAdminUser).getRecords();
		if(shopAdminUserList.size()==0){
			return CodeContent.getModelByCode(0, "您无权对该店铺的商品进行入库操作", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"goodsBePutInStorage" + inventory.getId());
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"goodsBePutInStorage" + inventory.getId(),10,"1");
		}
			int number=inventory.getInventory()+Integer.parseInt(changeNum);
			int totalNumber=inventory.getTotalInventory()+Integer.parseInt(changeNum);
			inventory.setInventory(number);
			inventory.setTotalInventory(totalNumber);
			inventory.setUpdateTime(new Date());
			inventory.setUpdateUserId(loginUser.getId());
			inventoryDao.modify(inventory);

		InventoryLog inventoryLog=new InventoryLog();
		inventoryLog.setInventoryId(inventory.getId());
		inventoryLog.setUserId(loginUser.getId());
		inventoryLog.setType(FlowType.Add);
		inventoryLog.setInventorySourceValue(Integer.parseInt(inventorySourceValue));
		inventoryLog.setChangeNum(Integer.parseInt(changeNum));
		inventoryLog.setCreateTime(new Date());
		String code = "RK"+ String.valueOf(new Date().getTime());
		inventoryLog.setCode(code);
		inventoryLog.setRemark(remark);
		inventoryLogDao.add(inventoryLog);
		return CodeContent.getModelByCode(1, "", model);
	}

	/*
*商品出库
* zlq
* token：
* inventorySourceValue: 来源
* changeNum:改变的值
* id：库存ID
* remark:备注
 */
	public String goodsOutput(ModelMap model,String token,String inventorySourceValue,String changeNum,String id,String remark) {
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (!NumberUtils.isDigits(inventorySourceValue)) {
			return CodeContent.getModelByCode(0, "库存来源不能为空", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "库存ID为空", model);
		}
		if (InventorySource.getByIntValue(Integer.parseInt(inventorySourceValue)) == null) {
			return CodeContent.getModelByCode(0, "库存来源不匹配", model);
		}
		if (!NumberUtils.isDigits(changeNum)) {
			return CodeContent.getModelByCode(0, "数量不能为空", model);
		}
		if (Integer.parseInt(changeNum) < 1) {
			return CodeContent.getModelByCode(0, "数量不能小于1", model);
		}
		Inventory inventory = inventoryDao.getById(Integer.parseInt(id));
		if(inventory==null){
			return CodeContent.getModelByCode(0, "无库存，不能进行出库操作", model);
		}else {
			ShopAdminUser shopAdminUser = new ShopAdminUser();
			shopAdminUser.setShopId(inventory.getShopId());
			shopAdminUser.setUserId(loginUser.getId());
			List<ShopAdminUser> shopAdminUserList = shopAdminUserDao.queryPageView(-1, -1, shopAdminUser).getRecords();
			if (shopAdminUserList.size() == 0) {
				return CodeContent.getModelByCode(0, "您无权对该店铺进行商品出库操作", model);
			}
			//防止重复提交
			Object o = memcached.get(inventory.getId()+"goodsOutput");
			if(o!=null){
				return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
			}else {
				memcached.set(inventory.getId()+"goodsOutput",10,"1");
			}
			if(inventory.getInventory()-Integer.parseInt(changeNum)<0){
				return CodeContent.getModelByCode(0, "库存不足", model);
			}
			int number=inventory.getInventory()-Integer.parseInt(changeNum);
			inventory.setInventory(number);
			inventory.setUpdateTime(new Date());
			inventory.setUpdateUserId(loginUser.getId());
			inventoryDao.modify(inventory);

			InventoryLog inventoryLog=new InventoryLog();
			inventoryLog.setInventoryId(inventory.getId());
			inventoryLog.setUserId(loginUser.getId());
			inventoryLog.setType(FlowType.Reduce);
			inventoryLog.setInventorySourceValue(Integer.parseInt(inventorySourceValue));
			inventoryLog.setChangeNum(Integer.parseInt(changeNum));
			inventoryLog.setCreateTime(new Date());
			String code = "CK"+ String.valueOf(new Date().getTime());
			inventoryLog.setCode(code);
			inventoryLog.setRemark(remark);
			inventoryLogDao.add(inventoryLog);
		}

		return CodeContent.getModelByCode(1, "", model);
	}

	/*
	*获取库存商品详情
	* zlq
	* token:
	*id:库存ID
	 */

	public String getInventoryDetails(ModelMap model,String id,String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		Inventory inventory=inventoryDao.getById(Integer.parseInt(id));
		if(inventory==null){
			return CodeContent.getModelByCode(0, "ID不正确", model);
		}
		GoodSpecification goodSpecification=null;
		if(inventory.getSpeciflcationId()!=null){
			goodSpecification=goodSpecificationDao.getById(inventory.getSpeciflcationId());
		}
		DdmShop ddmShop = ddmShopDao.getById(inventory.getShopId());
		if (ddmShop == null) {
			return CodeContent.getModelByCode(0, "店铺不存在", model);
		}
		DdmGoods ddmGoods = ddmGoodsDao.getById(inventory.getGoodsId());
		if (ddmGoods == null) {
			return CodeContent.getModelByCode(0, "商品不存在", model);
		}
		model.put("id",ddmGoods.getId());
		model.put("goodsId",ddmGoods.getId());
		model.put("abbreviation",ddmGoods.getAbbreviation());
		model.put("name",ddmGoods.getName());
		model.put("code",ddmGoods.getCode());
		model.put("memberPrice",goodSpecification!=null?goodSpecification.getMemberPrice():ddmGoods.getMemberPrice());
		model.put("propertiesName",goodSpecification!=null?goodSpecification.getPropertiesName():"");
		model.put("mainImg",ddmGoods.getMainImg());
		model.put("detailsImg",ddmGoods.getDetailsImg());
		model.put("goodsExplain",ddmGoods.getGoodsExplain());
		model.put("state",ddmGoods.getState()?"有效":"无效");
		model.put("isWarranty",ddmGoods.getIsWarranty()?"有保修":"无保修");
		model.put("warrantyPeriod",ddmGoods.getWarrantyPeriod()!=null?ddmGoods.getWarrantyPeriod()+"个月":"不保修");
		model.put("isImie",ddmGoods.getIsImie()?"有唯一码":"无唯一码");
		model.put("safeguard",ddmGoods.getSafeguard());
		model.put("parameter",ddmGoods.getParameter());
		model.put("inventory",inventory.getInventory());

		return CodeContent.getModelByCode(1, "", model);
	}

}